/**
 * @Author：ming
 * @Date：2023/9/29 3:24 PM
 * @Filename：Lc102
 */

import java.util.ArrayList;
import java.util.List;

/**
 * @author ming
 */
public class Lc102 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        ArrayList<TreeNode> parent = new ArrayList<>();
        ArrayList<TreeNode> child = new ArrayList<>();
        ArrayList<ArrayList<TreeNode>> lists = new ArrayList<>();
        List<List<Integer>> iList = new ArrayList<>();

        if(root==null){
            return iList;
        }

        parent.add(root);
        ArrayList<TreeNode> list2 = new ArrayList<>();
        for (TreeNode t : parent) {
            list2.add(t);
        }
        lists.add(list2);
        while (parent.size()!=0){
            TreeNode p = parent.get(0);
            if(p.left!=null){
                child.add(p.left);
            }
            if(p.right!=null){
                child.add(p.right);
            }
            parent.remove(0);

            if(parent.size()==0){
                if(child.size()==0){
                    break;
                }
                ArrayList<TreeNode> nodes = new ArrayList<>();
                for (TreeNode q : child) {
                    nodes.add(q);
                    parent.add(q);
                }
                lists.add(nodes);
                child.clear();

            }
        }

        for (ArrayList<TreeNode> list : lists) {
            ArrayList<Integer> list1 = new ArrayList<>();
            for (TreeNode treeNode : list) {
                list1.add(treeNode.val);
            }
            iList.add(list1);
        }

        return iList;
    }
}
